import http from './http'
import { requestWithRetry } from '@/utils/retry'

// 邀请API
export const invitationAPI = {
  // 生成邀请链接
  generateInvitation: async (data: { organizationId: number; email: string; role: string }) => {
    try {
      const result = await http.post('/invitations/generate', data);
      return {
        success: true,
        data: result
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '生成邀请链接失败'
      };
    }
  },

  // 验证邀请令牌
  validateInvitation: async (token: string) => {
    try {
      // 使用重试机制验证邀请令牌
      const response = await requestWithRetry(
        () => http.get('/invitations/validate', { params: { token } }),
        3, // 最多重试3次
        1000 // 基础延迟1秒
      );
      
      return {
        success: true,
        data: response.data
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '验证邀请链接失败'
      };
    }
  },

  // 接受邀请
  acceptInvitation: async (token: string) => {
    try {
      const result = await http.post('/invitations/accept', { token });
      return {
        success: true,
        data: result
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '接受邀请失败'
      };
    }
  },

  // 获取组织邀请列表
  getOrganizationInvitations: async (organizationId: number) => {
    try {
      // 使用重试机制获取组织邀请列表
      const response = await requestWithRetry(
        () => http.get('/invitations/organization', { params: { organizationId } }),
        3, // 最多重试3次
        1000 // 基础延迟1秒
      );
      
      return {
        success: true,
        data: response.data
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '获取邀请列表失败'
      };
    }
  },

  // 撤销邀请
  revokeInvitation: async (id: number) => {
    try {
      const result = await http.delete(`/invitations/${id}`);
      return {
        success: true,
        data: result
      };
    } catch (error: any) {
      return {
        success: false,
        data: null,
        message: error.message || '撤销邀请失败'
      };
    }
  }
}

export default invitationAPI